package common.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.DhcpInfo;
import android.net.Network;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.text.format.Formatter;

import com.android.volley.BuildConfig;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

import rx.Scheduler;
import rx.schedulers.Schedulers;

/**
 * Created by yinzhiqun on 2015/8/19.
 *
 */
public class NetUtil {


//    private static ScheduledExecutorService service = Executors.newScheduledThreadPool(8);
    private static Executor service = Executors.newFixedThreadPool(8);

    public static boolean checkNet(Context context) {
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = manager.getActiveNetworkInfo();
        return (info != null&&info.isConnected());
    }

    public static String getIp(Context context){
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = (InetAddress) enumIpAddr.nextElement();

                    if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return BuildConfig.IP;

//        WifiManager wifi_service = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
//        DhcpInfo dhcpInfo = wifi_service.getDhcpInfo();
//        WifiInfo wifiinfo = wifi_service.getConnectionInfo();
//        //DhcpInfo中的ipAddress是一个int型的变量，通过Formatter将其转化为字符串IP地址
//        return Formatter.formatIpAddress(dhcpInfo.ipAddress);
    }


    public static void execute(Runnable runnable){
        service.execute(runnable);
    }


    public static Scheduler scheduler = Schedulers.from(service);

    public static boolean isWIFINet(Context context){
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = manager.getActiveNetworkInfo();
        if (info != null&&info.isConnected()&&info.getTypeName().equalsIgnoreCase("WIFI")){
            return true;
        } else {
            return false;
        }
    }
}
